package cn.gene.timeyan.coo.webapi.service.impl;

import cn.gene.timeyan.common.constant.RedisConstants;
import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.common.restful.JsonPage;
import cn.gene.timeyan.common.restful.JsonResult;
import cn.gene.timeyan.common.restful.ResponseCode;
import cn.gene.timeyan.common.utils.FormUtils;
import cn.gene.timeyan.coo.service.CooperationService;
import cn.gene.timeyan.coo.webapi.mapper.CooperationMapper;
import cn.gene.timeyan.pojo.coo.dto.CooperationDTO;
import cn.gene.timeyan.pojo.coo.dto.CooperationDetailDTO;
import cn.gene.timeyan.pojo.coo.model.Cooperation;
import cn.gene.timeyan.pojo.coo.vo.CooperationVO;
import cn.gene.timeyan.pojo.ums.model.BrowsingHistory;
import cn.gene.timeyan.pojo.ums.vo.UserSimpleVO;
import cn.gene.timeyan.ums.service.IBrowsingHistoryService;
import cn.gene.timeyan.ums.service.IUserDetailService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 浜掑姪璐翠俊鎭 服务实现类
 * </p>
 *
 * @author LWG
 * @since 2022-07-25
 */
@Slf4j
@Service
public class CooperationServiceImpl  implements CooperationService {
    @Autowired(required = false)
    private CooperationMapper cooperationMapper;
    @DubboReference
    private IBrowsingHistoryService dubboBrowsingHistory;
    @DubboReference
    private IUserDetailService dubboUserDetail;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    @Qualifier("redisTemplate2")
    private RedisTemplate redisTemplate2;
    @Override
    public Cooperation getHelpByHelpId(Long helpId){ return cooperationMapper.getHelpByHelpId(helpId);}

    /**DJM**///
    @Override
    public CooperationVO cooperationDetail(CooperationDetailDTO cooperationDetailDTO) {
        CooperationVO cooperationVO = cooperationMapper.getDetail(cooperationDetailDTO);
        //获取求助者信息
        UserSimpleVO user=dubboUserDetail.selectUserCommentVOByUserId(cooperationDetailDTO.getUserId());
        cooperationVO.setUserInfo(user);
        return cooperationVO;
    }

    @Override
    public JsonPage<Cooperation> getCooperationByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Cooperation> list = cooperationMapper.findAllList();
        return JsonPage.restPage(new PageInfo<>(list));
    }

    @Override
    public JsonPage<Cooperation> getCooperationLostByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Cooperation> list = cooperationMapper.findLostList();
        return JsonPage.restPage(new PageInfo<>(list));
    }

    @Autowired(required = false)
    private Cooperation cooperation;

    /**
     * 发布求助
     */
    @Override
    public void addNewCooperation(CooperationDTO cooperationDTO) {
        log.trace("业务逻辑层，开始发布求助业务");
        log.trace("尝试添加的求助信息: {}" + cooperationDTO);

        //创建Cooperation对象
        Cooperation cooperation = new Cooperation();
        //补全对象属性
        BeanUtils.copyProperties(cooperationDTO, cooperation);
        cooperation.setDifficulty("1");

        //创建当前时间对象
        Date now=new Date();
        cooperation.setCreateTime(now);
        cooperation.setUpdateTime(now);

        log.trace("补全属性完毕:" + cooperation);
        //添加到互助表hms_cooperation中，查看返回值
        int rows = cooperationMapper.insert(cooperation);

        //判断rows的结果是否为1
        if (rows != 1) {
            log.error("添加失败，将抛出异常");
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "发布求助失败，服务器忙，请稍后再次尝试！");
        }

    }

    @Override
    public int updateApplyBelimit(Long helpId) {
        //row代表更新行数
        int row = cooperationMapper.updateApplyBelimit(helpId);
        return row;
    }

    /**
     * 获取校园区互助列表
     * @param school
     * @param modelId
     * @return
     */
    @Override
    public List<CooperationVO> getCooperationList(String school, Long modelId) {
        String key= RedisConstants.HELP_LIST+school+":"+"model"+modelId+":";
        List<CooperationVO> list=new ArrayList<>();
        //检查缓存
        if (redisTemplate.hasKey(key)){
            //有缓存,获取30个结果的id
            Set<String> set=redisTemplate.opsForZSet().reverseRange(key+"time",0,29);
            for (String id:set) {
                CooperationVO cooperationVO= JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(),CooperationVO.class);
                list.add(cooperationVO);
            }
//            if (list.size()<30){
//                throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
//            }
            return list;
        }
        //没缓存
        //获取互助
        PageHelper.startPage(1,30);
        List<CooperationVO> helps=cooperationMapper.getHelpList(school,modelId);
        if (helps==null ||helps.size()==0){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
        }
        Map<String,Object> map=new HashMap<>();
        //存入缓存
        for (CooperationVO help:helps) {
            //获取互助信息
            if (help.getHelpContent().length()>50){
                help.setHelpContent(help.getHelpContent().substring(0,50)+"...");
            }else{
                help.setHelpContent(help.getHelpContent());
            }
            double time= FormUtils.parseTimeByDate(help.getCreateTime());
            //获取作者信息
            UserSimpleVO user=dubboUserDetail.selectUserCommentVOByUserId(help.getUserId());
            help.setUserInfo(user);
            //把互助id作为value
            redisTemplate.opsForZSet().add(key+"time",""+help.getHelpId(),time);
            map.put(""+help.getHelpId(),JSON.toJSON(help));
            list.add(help);
        }
        redisTemplate.opsForHash().putAll(key+"detail",map);
//        if (list.size()<30){
//            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
//        }
        return list;
    }

    /**
     * 校园区互助信息列表再加载
     * @param school
     * @param modelId
     * @param page
     * @return
     */
    @Override
    public List<CooperationVO> getHelpListNext(String school, Long modelId, Integer page) {
        String key= RedisConstants.HELP_LIST+school+":"+"model"+modelId+":";
        List<CooperationVO> list=new ArrayList<>();
        //检查缓存
        if (redisTemplate.hasKey(key+"time")){
            long total=30+page*10;
            //数量足够
            if(redisTemplate.opsForZSet().size(key+"time")>=total){
                //获取10个新数据返回
                Set<String> ids=redisTemplate.opsForZSet().reverseRange(key+"time",total-10,total-1);
                for (String id:ids) {
                    CooperationVO heplVO=JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(),CooperationVO.class);
                    list.add(heplVO);
                }
                return list;
            }
            //数量不够，数据库获取30条
            PageHelper.startPage(page/2+2,30);
            List<CooperationVO> helpList=cooperationMapper.getHelpList(school,modelId);
            if (helpList==null ||helpList.size()==0){
                throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
            }
            Map<String,Object> map=new HashMap<>();
            //存入缓存
            for (CooperationVO help:helpList) {
                //获取互助信息
                if (help.getHelpContent().length()>50){
                    help.setHelpContent(help.getHelpContent().substring(0,50)+"...");
                }else{
                    help.setHelpContent(help.getHelpContent());
                }
                double time= FormUtils.parseTimeByDate(help.getCreateTime());
                //获取作者信息
                UserSimpleVO user=dubboUserDetail.selectUserCommentVOByUserId(help.getUserId());
                help.setUserInfo(user);
                //把互助id作为value
                redisTemplate.opsForZSet().add(key+"time",""+help.getHelpId(),time);
                map.put(""+help.getHelpId(),JSON.toJSON(help));
            }
            redisTemplate.opsForHash().putAll(key+"detail",map);
            //获取缓存
            //获取10个新数据返回
            Set<String> ids=redisTemplate.opsForZSet().reverseRange(key+"time",total-10,total-1);
            for (String id:ids) {
                CooperationVO helpVO=JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(),CooperationVO.class);
                list.add(helpVO);
            }
            return list;
        }
        //没缓存
        //获取互助
        PageHelper.startPage(1,30);
        List<CooperationVO> helps=cooperationMapper.getHelpList(school,modelId);
        if (helps==null ||helps.size()==0){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
        }
        Map<String,Object> map=new HashMap<>();
        //存入缓存
        for (CooperationVO help:helps) {
            //获取互助信息
            if (help.getHelpContent().length()>50){
                help.setHelpContent(help.getHelpContent().substring(0,50)+"...");
            }else{
                help.setHelpContent(help.getHelpContent());
            }
            double time= FormUtils.parseTimeByDate(help.getCreateTime());
            //获取作者信息
            UserSimpleVO user=dubboUserDetail.selectUserCommentVOByUserId(help.getUserId());
            help.setUserInfo(user);
            //把互助id作为value
            redisTemplate.opsForZSet().add(key+"time",""+help.getHelpId(),time);
            map.put(""+help.getHelpId(),JSON.toJSON(help));
            list.add(help);
        }
        redisTemplate.opsForHash().putAll(key+"detail",map);
//        if (list.size()<30){
//            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
//        }
        return list;
    }

    /**
     * 全国区互助列表获取
     * @param modelId
     * @return
     */
    @Override
    public List<CooperationVO> getCountryCooperationList(Long modelId) {
        String key= RedisConstants.HELP_LIST+"全国:"+"model"+modelId+":";
        List<CooperationVO> list=new ArrayList<>();
        //检查缓存
        if (redisTemplate.hasKey(key)){
            //有缓存,获取30个结果的id
            Set<String> set=redisTemplate.opsForZSet().reverseRange(key+"time",0,29);
            for (String id:set) {
                CooperationVO cooperationVO= JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(),CooperationVO.class);
                list.add(cooperationVO);
            }
//            if (list.size()<30){
//                throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
//            }
            return list;
        }
        //没缓存
        //获取互助
        PageHelper.startPage(1,30);
        List<CooperationVO> helps=cooperationMapper.getHelpListByModelId(modelId);
        if (helps==null ||helps.size()==0){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
        }
        Map<String,Object> map=new HashMap<>();
        //存入缓存
        for (CooperationVO help:helps) {
            //获取互助信息
            if (help.getHelpContent().length()>50){
                help.setHelpContent(help.getHelpContent().substring(0,50)+"...");
            }else{
                help.setHelpContent(help.getHelpContent());
            }
            double time= FormUtils.parseTimeByDate(help.getCreateTime());
            //获取作者信息
            UserSimpleVO user=dubboUserDetail.selectUserCommentVOByUserId(help.getUserId());
            help.setUserInfo(user);
            //把互助id作为value
            redisTemplate.opsForZSet().add(key+"time",""+help.getHelpId(),time);
            map.put(""+help.getHelpId(),JSON.toJSON(help));
            list.add(help);
        }
        redisTemplate.opsForHash().putAll(key+"detail",map);
//        if (list.size()<30){
//            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
//        }
        return list;
    }

    /**
     * 全国区互助列表再加载
     * @param modelId
     * @param page
     * @return
     */
    @Override
    public List<CooperationVO> getCountryHelpListNext(Long modelId, Integer page) {
        String key= RedisConstants.HELP_LIST+"全国:"+"model"+modelId+":";
        List<CooperationVO> list=new ArrayList<>();
        //检查缓存
        if (redisTemplate.hasKey(key+"time")){
            long total=30+page*10;
            //数量足够
            if(redisTemplate.opsForZSet().size(key+"time")>=total){
                //获取10个新数据返回
                Set<String> ids=redisTemplate.opsForZSet().reverseRange(key+"time",total-10,total-1);
                for (String id:ids) {
                    CooperationVO heplVO=JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(),CooperationVO.class);
                    list.add(heplVO);
                }
                return list;
            }
            //数量不够，数据库获取30条
            PageHelper.startPage(page/2+2,30);
            List<CooperationVO> helpList=cooperationMapper.getHelpListByModelId(modelId);
            if (helpList==null ||helpList.size()==0){
                throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
            }
            Map<String,Object> map=new HashMap<>();
            //存入缓存
            for (CooperationVO help:helpList) {
                //获取互助信息
                if (help.getHelpContent().length()>50){
                    help.setHelpContent(help.getHelpContent().substring(0,50)+"...");
                }else{
                    help.setHelpContent(help.getHelpContent());
                }
                double time= FormUtils.parseTimeByDate(help.getCreateTime());
                //获取作者信息
                UserSimpleVO user=dubboUserDetail.selectUserCommentVOByUserId(help.getUserId());
                help.setUserInfo(user);
                //把互助id作为value
                redisTemplate.opsForZSet().add(key+"time",""+help.getHelpId(),time);
                map.put(""+help.getHelpId(),JSON.toJSON(help));
            }
            redisTemplate.opsForHash().putAll(key+"detail",map);
            //获取缓存
            //获取10个新数据返回
            Set<String> ids=redisTemplate.opsForZSet().reverseRange(key+"time",total-10,total-1);
            for (String id:ids) {
                CooperationVO helpVO=JSON.parseObject(redisTemplate.opsForHash().get(key+"detail",id).toString(),CooperationVO.class);
                list.add(helpVO);
            }
            return list;
        }
        //没缓存
        //获取互助
        PageHelper.startPage(1,30);
        List<CooperationVO> helps=cooperationMapper.getHelpListByModelId(modelId);
        if (helps==null ||helps.size()==0){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
        }
        Map<String,Object> map=new HashMap<>();
        //存入缓存
        for (CooperationVO help:helps) {
            //获取互助信息
            if (help.getHelpContent().length()>50){
                help.setHelpContent(help.getHelpContent().substring(0,50)+"...");
            }else{
                help.setHelpContent(help.getHelpContent());
            }
            double time= FormUtils.parseTimeByDate(help.getCreateTime());
            //获取作者信息
            UserSimpleVO user=dubboUserDetail.selectUserCommentVOByUserId(help.getUserId());
            help.setUserInfo(user);
            //把互助id作为value
            redisTemplate.opsForZSet().add(key+"time",""+help.getHelpId(),time);
            map.put(""+help.getHelpId(),JSON.toJSON(help));
            list.add(help);
        }
        redisTemplate.opsForHash().putAll(key+"detail",map);
//        if (list.size()<30){
//            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙");
//        }
        return list;
    }

    /**
     * 获取用户发表的户主列表
     * @param userId
     * @param page
     * @return
     */
    @Override
    public JsonResult<List<CooperationVO>> getUserHelpList(Long userId, Integer page) {
        //判断参数正确与否
        if (userId==null||page==null||page<1){
            throw new TimeyanServiceException(ResponseCode.ERR_NOTIME,"系统繁忙");
        }
        //查询该用户发表的分享信息
        //查询30个
        PageHelper.startPage(page,30);
        List<CooperationVO> helps=cooperationMapper.getHelpListByUserId(userId);
        System.out.println("helps:"+helps);
        if (helps==null ||helps.size()==0){
            throw new TimeyanServiceException(ResponseCode.ERR_NOTIME,"系统繁忙");
        }
        return JsonResult.ok(helps);
    }


    //保存浏览记录
    private boolean saveBrowsing(CooperationDTO cooperationDTO){
        BrowsingHistory history=new BrowsingHistory();
        history.setUserId(cooperationDTO.getUserId());
        history.setModuleId(cooperationDTO.getModuleId());
        history.setSourceId(cooperationDTO.getHelpId());
        history.setModuleType("1");
        history.setViewTime(LocalDateTime.now());
        dubboBrowsingHistory.addBrowsingHistory(history);
        return true;
    }
}
